import socket, sys, os, django, time
from datetime import datetime, timedelta

sys.path.append("/Volumes/mobile/code/mine/guanxian/ht_guangxian/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cate.settings")
django.setup()

import django.utils.timezone as timezone
from device.models import temperatureInfo, channelInfo, deviceInfo


def parseMessageTrace(msg):
    data_type = ''
    temp_res = True if msg[:16] == 'AA7B07AFEC6648C5' and msg[-2:] == '55' else False
    constant_res = True if msg[:16] == 'A67B07AFEC6648C5' and msg[-2:] == '55' else False
    offline_res = True if msg[:16] == 'BC7B07AFEC6648C5' and msg[-2:] == '55' else False
    poor_res = True if msg[:16] == 'A57B07AFEC6648C5' and msg[-2:] == '55' else False
    if temp_res == True:
        data_type = 'temperature'
    elif constant_res == True:
        data_type = 'constant'
    elif offline_res == True:
        data_type = 'offline'
    elif poor_res == True:
        data_type = 'poor'
    if data_type == '':
        return ''
    data_length_temp = msg[20:22] + msg[18:20]
    data_length = int(data_length_temp, 16)
    actual_length = len(msg)/2
    if data_length != actual_length:
        return ''
    return data_type

def handleTemperatureData(tongdao_temp, hex_str, start_value):
    chunks = [hex_str[i:i+4] for i in range(0, len(hex_str), 4)]
    reversed_chunks = []
    temperatureList = []
    channelData = channelInfo.objects.get(id=tongdao_temp)
    for chunk in chunks:
        this_data = {}
        part1 = chunk[:2]
        part2 = chunk[2:]
        reversed_chunk = part2 + part1
        # print('reversed_chunk:', reversed_chunk)
        decimal_value = (int(reversed_chunk, 16)-20000)/100
        this_data['meter'] = start_value
        this_data['temperature'] = decimal_value
        if decimal_value > 0:
            temperatTemp = temperatureInfo(
                belong_channel=channelData, meter_address=start_value, temperature_info=decimal_value, order_time=timezone.now(),
            )
            temperatureList.append(temperatTemp)
            channelInfo.objects.filter(id=tongdao_temp).update(is_valid=True)
        else:
            channelInfo.objects.filter(id=tongdao_temp).update(is_valid=False)
        start_value += 0.5
        reversed_chunks.append(this_data)
    temperatureInfo.objects.bulk_create(temperatureList)
    return reversed_chunks


if __name__ == "__main__":
    this_tongdao_tmp= 1
    temp_info = temperatureInfo.objects.filter(belong_channel__id=this_tongdao_tmp).latest('order_time')
    latest_order_time = temp_info.order_time.strftime('%Y-%m-%d %H:%M:%S')
    # print('latest_order_time:', latest_order_time)


    # 获取一小时前到最新下单时间之间的所有数据
    # data_within_one_hour = list(temperatureInfo.objects.filter(belong_channel__id=this_tongdao_tmp).values('id', 'belong_channel','meter_address', 'temperature_info', 'order_time'))
    # print('data_within_one_hour:', data_within_one_hour)

    message_temp = 'AA7B07AFEC6648C57323000000FF0000000600080004CB56F8569D56AF56B3563F5755'
    # message = ''.join([i.strip(' ') for i in message_temp])
    checkRes = parseMessageTrace(message_temp)
    # print('checkRes:', checkRes)
    # 处理解析数据
    if checkRes != '':
        if checkRes == 'temperature':
            start_temp = message_temp[30:34]
            start_value = int(start_temp[2:] + start_temp[:2], 16)

            end_temp = message_temp[34:38]
            end_value = int(end_temp[2:] + end_temp[:2], 16)

            tongdao_temp = message_temp[42:44]
            sys_tongdao_temp =  int(tongdao_temp) + 1
            data_temp = message_temp[44:-2]
            # time_start = time.time()  # 记录开始时间
            # print('time_start:',time_start)
            this_data = handleTemperatureData(sys_tongdao_temp, data_temp, start_value)
            # time_end = time.time()  # 记录结束时间
            # print('time_end:',time_end)
            # time_sum = time_end - time_start  # 计算的时间差为程序的执行时间，单位为秒/s
            # print('total_time:',time_sum)
            # print('this_data:', tongdao_temp, this_data)